import 'package:dio/dio.dart' as dio;
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import '../services/dio_service.dart';
import '../models/index.dart';

/// 短视频API调用类
/// 
/// 负责所有短视频相关的API调用
/// 对应Android原生的 HttpApiAppShortVideo 接口类
class ShortVideoApi {
  // 🔗 API路径常量
  static const String getUserShortVideoPagePath = '/api/shortvideo/getUserShortVideoPage';
  static const String getShortVideoListPath = '/api/shortvideo/getShortVideoList';
  static const String shortVideoZanPath = '/api/shortvideo/shortVideoZan';
  
  // 📡 网络服务实例
  static DioService get _dioService => Get.find<DioService>();
  
  /// 获取用户短视频列表(分页)
  /// 
  /// 对应Android原生的 getUserShortVideoPage 接口
  /// [page] 页数(从1开始)
  /// [pageSize] 每页条数
  /// [toUid] 对方用户ID(传-1查询自己的)
  /// [type] 类型 0:推荐 1:我的作品 2:我喜欢的 3:我购买的 4:历史 5:私密
  /// 
  /// 返回 ApiShortVideoPageResult 包含短视频列表和分页信息
  static Future<ApiShortVideoPageResult> getUserShortVideoPage({
    required int page,
    required int pageSize,
    int toUid = -1,
    required int type,
  }) async {
    try {
      debugPrint('🎬 开始获取用户短视频列表');
      debugPrint('📤 请求参数: page=$page, pageSize=$pageSize, toUid=$toUid, type=$type');
      
      // 类型说明
      final typeMap = {
        0: '推荐',
        1: '我的作品',
        2: '我喜欢的',
        3: '我购买的',
        4: '历史',
        5: '私密',
      };
      debugPrint('📝 查询类型: ${typeMap[type] ?? '未知'}');
      
      // 使用form-data格式(对标Android原生)
      final response = await _dioService.post(
        getUserShortVideoPagePath,
        data: {
          'page': page,
          'pageSize': pageSize,
          'toUid': toUid,  // -1查询自己
          'type': type,
        },
        options: dio.Options(
          contentType: dio.Headers.formUrlEncodedContentType,
        ),
      );
      
      debugPrint('📥 短视频列表响应状态: ${response.statusCode}');
      
      // 解析响应数据
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final code = responseData['code']?.toInt() ?? 0;
        final msg = responseData['msg']?.toString() ?? '';
        
        debugPrint('📥 响应code: $code, msg: $msg');
        
        if (code == 1) {
          // 成功响应 - 数据在retArr字段(对标Android返回格式)
          final retArr = responseData['retArr'];
          final pageSize = responseData['pageSize'] ?? 0;
          final pageIndex = responseData['pageIndex'] ?? 0;
          final outTotalPage = responseData['outTotalPage'] ?? 0;
          final outTotalCount = responseData['outTotalCount'] ?? 0;
          
          if (retArr != null && retArr is List) {
            // ✅ 解析retArr数组
            List<dynamic> videoList = retArr;
            
            // 解析短视频列表
            final videos = videoList
                .map((json) => ApiShortVideoDto.fromJson(json as Map<String, dynamic>))
                .toList();
            
            // 构建分页信息(对标Android格式)
            final pageInfo = {
              'pageSize': pageSize,
              'pageIndex': pageIndex,
              'outTotalPage': outTotalPage,
              'outTotalCount': outTotalCount,
            };
            
            debugPrint('✅ 获取短视频列表成功');
            debugPrint('📊 数据统计:');
            debugPrint('  - 返回数量: ${videos.length}');
            debugPrint('  - 当前页: $pageIndex');
            debugPrint('  - 每页大小: $pageSize');
            debugPrint('  - 总记录数: $outTotalCount');
            debugPrint('  - 总页数: $outTotalPage');
            
            // 返回结果
            // ⚠️ hasMore判断：
            // 1. 如果outTotalPage > 0，则使用标准分页判断
            // 2. 如果outTotalPage = 0但有数据返回，说明还有更多数据（服务器未返回分页信息）
            final bool hasMoreData;
            if (outTotalPage > 0) {
              hasMoreData = pageIndex < outTotalPage;
            } else {
              // 没有分页信息时，根据返回数据量判断
              // 如果返回数据量等于pageSize，说明可能还有更多数据
              hasMoreData = videos.length >= pageSize;
            }
            
            return ApiShortVideoPageResult(
              videos: videos,
              pageInfo: pageInfo,
              hasMore: hasMoreData,
            );
          } else {
            debugPrint('⚠️ 返回空数据');
            return ApiShortVideoPageResult.empty();
          }
        } else {
          // 业务失败响应
          debugPrint('❌ 获取短视频列表失败: $msg');
          throw Exception(msg.isNotEmpty ? msg : '获取短视频列表失败');
        }
      } else {
        debugPrint('❌ 服务器响应格式错误');
        throw Exception('服务器响应格式错误');
      }
    } catch (e) {
      debugPrint('❌ 获取短视频列表API异常: $e');
      rethrow;
    }
  }
  
  /// 短视频点赞/取消点赞
  /// 
  /// [shortVideoId] 短视频ID
  /// 返回是否成功
  static Future<bool> shortVideoZan(int shortVideoId) async {
    try {
      debugPrint('👍 短视频点赞/取消: $shortVideoId');
      
      final response = await _dioService.post(
        shortVideoZanPath,
        data: {
          'shortVideoId': shortVideoId,
        },
        options: dio.Options(
          contentType: dio.Headers.formUrlEncodedContentType,
        ),
      );
      
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseData = response.data as Map<String, dynamic>;
        final code = responseData['code']?.toInt() ?? 0;
        final msg = responseData['msg']?.toString() ?? '';
        
        if (code == 1) {
          debugPrint('✅ 点赞操作成功');
          return true;
        } else {
          debugPrint('❌ 点赞操作失败: $msg');
          throw Exception(msg.isNotEmpty ? msg : '点赞操作失败');
        }
      } else {
        throw Exception('服务器响应格式错误');
      }
    } catch (e) {
      debugPrint('❌ 点赞操作异常: $e');
      rethrow;
    }
  }
}

/// 短视频分页查询结果
class ApiShortVideoPageResult {
  final List<ApiShortVideoDto> videos;
  final Map<String, dynamic>? pageInfo;
  final bool hasMore;
  
  ApiShortVideoPageResult({
    required this.videos,
    this.pageInfo,
    this.hasMore = false,
  });
  
  factory ApiShortVideoPageResult.empty() {
    return ApiShortVideoPageResult(
      videos: [],
      pageInfo: null,
      hasMore: false,
    );
  }
}

